package com.example.myjavafx.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.example.myjavafx.model.User;
import com.example.myjavafx.model.UserDto;
import com.example.myjavafx.model.Users;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

import java.lang.reflect.Type;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ApiService {
    // 获取视频流的方法
    public static void fetchVideoStream(VideoStreamCallback onSuccess, ErrorCallback onError) {
        new Thread(() -> {
            try {
                // 替换为实际的API端点
//                URL url = new URL("http://your-api-endpoint/video-stream");
//                String defaultVideoPath = ApiService.class.getResource("/videos/视频1.mp4").toExternalForm();

                URL url = new URL("http://localhost:8080/api/video-stream");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");

                // 读取二进制流数据
                try (InputStream is = conn.getInputStream();
                     ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
                    int nRead;
                    byte[] data = new byte[16384];
                    while ((nRead = is.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, nRead);
                    }
                    buffer.flush();

                    byte[] videoData = buffer.toByteArray();

                    // 在JavaFX应用程序线程中处理结果
                    javafx.application.Platform.runLater(() -> {
                        onSuccess.onSuccess(videoData);
                    });
                }
            } catch (Exception e) {
                javafx.application.Platform.runLater(() -> {
                    onError.onError(e.getMessage());
                });
            }
        }).start();
    }

    // 视频流回调接口
    public interface VideoStreamCallback {
        void onSuccess(byte[] videoData);
    }

    // 错误回调接口
    public interface ErrorCallback {
        void onError(String error);
    }

    private static final String API_URL = "http://localhost:8080/api/users";

    // 异步获取用户列表
    public static void fetchUsers(Consumer<List<Users>> onSuccess, Consumer<String> onError) {
        HttpClient client = HttpClient.newHttpClient();
//        String requestBody = "{\"username\":\"张三\",\"password\":\"123456\"}";
        String requestBody = "{\"id\":12345,\"name\":\"lichuandi\"}";

//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(URI.create("http://localhost:9010/api/user"))
//                .header("Content-Type", "application/json") // 设置请求头
//                .POST(HttpRequest.BodyPublishers.ofString(requestBody)) // 设置请求体
//                .build();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .build();

        // 异步发送请求
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(response -> {
                    List<Users> users = parseJson(response); // 解析JSON
                    Platform.runLater(() -> onSuccess.accept(users)); // 回到UI线程更新
                })
                .exceptionally(e -> {
                    Platform.runLater(() -> onError.accept("请求失败: " + e.getMessage()));
                    return null;
                });
    }

    public static List<User> getUsers() {
//        return List.of(
//                new User(1,"张三","123455" ,25),
//                new User(1,"张三","123455" ,25)
//        );

        return null;
    }
    // 解析JSON（假设返回格式为：[{"name":"张三","age":25}, ...]）
    private static List<Users> parseJson(String json) {
        // 实际项目中使用 Jackson/Gson 等库，这里简化处理
        System.out.println(json + "解析JSON");
        // 示例返回数据，实际应用中应从JSON字符串解析得到
//        List<User> users = UserDto.parseJson(json);
        List<Users> users = UserDto.parseJsonToList(json);
//        Gson gson = new Gson();
//        // 使用转换
//        Type userListType = new TypeToken<List<User>>(){}.getType();
//        List<User> users = gson.fromJson(json, userListType);
//        List<UserDto> userDtos = gson.fromJson(json, userListType);
//        List<User> users = new ArrayList<>();
//        for (UserDto dto : userDtos) {
//            users.add(fromDto(dto));
//        }
//
//        User user = gson.fromJson(json, User.class);
//        StringProperty userName = new SimpleStringProperty(user.getUser_name());
//        StringProperty user_password = new SimpleStringProperty(user.getUser_password());
//        user.setUser_name(userName.get());

        System.out.println(json + " 已解析为 User 列表");
//        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
//        int id = jsonObject.get("id").getAsInt();
//        String userName = jsonObject.get("user_name").getAsString();
//        String userPassword = jsonObject.get("user_password").getAsString();
//        int age = jsonObject.get("age").getAsInt();
//        User user = User.fromJsonData(id, userName, userPassword, age);

        return users;

//        return List.of(
//                new User("张三", 25),
//                new User("李四", 30)
//        );
    }
}